Notification service
This documentation is to explain how the notification service works.
Methods
getSender
private getSender = async (profileId: number, profiles: ProfileRS[]): Promise<ProfileRS | null> => {
try {
if (!profileId) return null;
// get the profileId in the list
let sender = profiles.find((profile) => profile.id === profileId);
if (!sender) {
sender = await getProfile(profileId);
}
return sender;
} catch (error) {
console.error('Error getting sender', error);
throw new ApiError('Error getting sender', 500, ErrorsEnum.internalServerError);
}
};
This function is used to get the profile informations of the sender of the notification. It takes the following parameters:
profileId: The ID of the profile sending the notification.profiles: The list of profiles to search in.
In first time, it will search in the list of profiles. If the profile is not found, it will call the getProfile function to get the profile informations.
removeSender
private removeSender = (profileId: number, profiles: ProfileRS[]): ProfileRS[] => {
if (!profileId) return profiles;
// remove the profile that triggered the notification
profiles.splice(
profiles.findIndex((profile) => profile.id === profileId),
1,
);
return profiles;
};
This function is used to remove the sender of the notification from the list of profiles. It takes the following parameters:
profileId: The ID of the profile sending the notification.profiles: The list of profiles to search in.
getProfileAndUserIds
private getProfileAndUserIds = async (profileId: number, profiles: ProfileRS[]) => {
const sender = await this.getSender(profileId, profiles);
const receivers = this.removeSender(profileId, profiles);
const userIds = receivers.map((reciever) => reciever.userId);
return { sender, userIds };
};
This function is used to get the sender of the notification and the list of user IDs of the receivers. It takes the following parameters:
profileId: The ID of the profile sending the notification.profiles: The list of profiles to search in.
In first time, it will call the getSender method to get the sender of the notification. Then, it will call the removeSender method to remove the sender from the list of profiles. Finally, it will return the sender and the list of user IDs of the receivers.
notifyUser
notifyUser = async (
userId: string,
notifType: number,
language: string,
custom?: any,
options?: NotificationOptions,
sender?: ProfileRS,
): Promise<string> => {
try {
return await this.notifyUsers([userId], notifType, language, custom, options, sender);
} catch (error) {
console.error('Error sending notification', error);
throw new ApiError('Error sending notification', 500, ErrorsEnum.internalServerError);
}
};
This method is used to send a notification to a specific user. It takes the following parameters:
userId: The ID of the user.notifType: The type of notification.language: The language of the notification.custom: Custom data to be sent with the notification.options: Additional options for the notification.sender: The profile of the sender of the notification.
It will call the notifyUsers method with the list of user IDs containing only the user ID.
notifyUsers
notifyUsers = async (
userIds: string[],
notifType: number,
language: string,
custom?: any,
options?: NotificationOptions,
sender?: ProfileRS,
): Promise<string> => {
try {
const notif = getNotificationContent(notifType, language);
const notificationId: string = v4();
const notifications = userIds.map((userId) => ({
receiverId: userId,
category: notif.category || NotificationCategory.information,
notificationId,
createdAt: new Date().toISOString(),
type: notifType,
status: NotificationStatus.unread,
senderId: sender ? sender.id : 0,
senderName: sender ? `${sender.firstName} - ${sender.lastName}` : '',
custom: custom || {},
expirationTime: notif?.options?.expirationTime || options?.expirationTime || addMonthsToEpoch(6),
})) as Notification[];
// save notifications
await createNotifications(notifications);
// Send notification
const updateEvent: UpdateEvent = createNotifEvent(
notif.title,
notif.content,
notifType,
options?.id ?? notificationId,
options?.type,
notif?.options?.duration ?? options?.duration,
options?.placement,
custom,
);
await sendUpdateUsers(userIds, updateEvent);
return notificationId;
} catch (error) {
console.error('Error sending notification', error);
throw new ApiError('Error sending notification', 500, ErrorsEnum.internalServerError);
}
};
This method is used to send a notification to a list of users. It takes the following parameters:
userIds: The list of user IDs to send the notification to.notifType: The type of notification.language: The language of the notification.custom: Custom data to be sent with the notification.options: Additional options for the notification.sender: The profile of the sender of the notification.
In first time, it will get the content of the notification. Then, it will create the notifications to save in the database. Finally, it will send the notification to the users.
notifyOrgaManager
notifyOrgaManager = async (
orgId: number,
notifType: number,
language: string,
custom?: any,
options?: NotificationOptions,
profileId?: number,
): Promise<string> => {
try {
const profiles = await getManagerProfilesOfOrga(orgId);
const { sender, userIds } = await this.getProfileAndUserIds(profileId!, profiles);
return await this.notifyUsers(userIds, notifType, language, custom, options, sender!);
} catch (error) {
console.error('Error sending notification', error);
throw new ApiError('Error sending notification', 500, ErrorsEnum.internalServerError);
}
};
This method is used to send a notification to all managers of an organization. It takes the following parameters:
orgId: The ID of the organization.notifType: The type of notification.language: The language of the notification.custom: Custom data to be sent with the notification.options: Additional options for the notification.profileId: The ID of the profile sending the notification.
The method use the getProfileAndUserIds method to extract the sender and the list of user IDs of the receivers.
notifySiteManager
notifySiteManager = async (
orgId: number,
siteId: number,
notifType: number,
language: string,
custom?: any,
options?: NotificationOptions,
profileId?: number,
): Promise<string> => {
try {
const profiles = await getManagerProfilesOfSite(orgId, siteId);
const { sender, userIds } = await this.getProfileAndUserIds(profileId!, profiles);
return await this.notifyUsers(userIds, notifType, language, custom, options, sender!);
} catch (error) {
console.error('Error sending notification', error);
throw new ApiError('Error sending notification', 500, ErrorsEnum.internalServerError);
}
};
This method is used to send a notification to all managers of a site. It takes the following parameters:
orgId: The ID of the organization.siteId: The ID of the site.notifType: The type of notification.language: The language of the notification.custom: Custom data to be sent with the notification.options: Additional options for the notification.profileId: The ID of the profile sending the notification.
The method use the getProfileAndUserIds method to extract the sender and the list of user IDs of the receivers. And, it will call the notifyUsers method to send the notification.
updateActionNotification
updateActionNotification = async (notifId: string, profileId: number): Promise<void> => {
try {
const profile = await getProfile(profileId);
const doneActionInfo: DoneActionInfo = {
doneBy: `${profile.firstName} - ${profile.lastName}`,
doneById: profile.userId,
doneAt: new Date().toISOString(),
doneCustom: {},
};
await updateActionNotification(notifId, doneActionInfo);
} catch (error) {
console.error('Error updating notification', error);
throw new ApiError('Error updating notification', 500, ErrorsEnum.internalServerError);
}
};
This method is used to update an action notification. It takes the following parameters:
notifId: The ID of the notification.profileId: The ID of the profile updating the notification.
getNotificationContent
export const getNotificationContent = (notifType: number, language: string) => {
const langTranslations = translations[language] || translations.fr;
switch (notifType) {
case NotificationType.intervention_finish:
return {
title: langTranslations.intervention_finish.title,
content: langTranslations.intervention_finish.content,
category: NotificationCategory.information,
options: { duration: 0, expirationTime: addYearsToEpoch(1) },
};
case NotificationType.report_submit:
return {
title: langTranslations.report_submit.title,
content: langTranslations.report_submit.content,
category: NotificationCategory.information,
options: { duration: 0, expirationTime: addYearsToEpoch(1) },
};
case NotificationType.observation_created:
return {
title: langTranslations.observation_created.title,
content: langTranslations.observation_created.content,
category: NotificationCategory.information,
options: { duration: 0, expirationTime: addYearsToEpoch(1) },
};
default:
return {
title: 'Unknown title',
content: 'Unknow content',
};
}
};
This function is used to get the content of a notification based on the type and the language. It takes the following parameters:
notifType: The type of notification.language: The language of the notification.
It will return the title, the content, the category and the options of the notification.
Usages examples
Send a notification to the organisation managers when an intervention is finished:
import NotificationService from '@shared/services/notification-service';
const notificationService = new NotificationService();
export const handler = (event: any, context: any) => {
const { organizationId: orgId } = context.clientContext?.Custom.sessionToken || {};
const token = getUserData(event) as AccessToken;
const language = token.lang || 'fr';
await notificationService.notifyOrgaManager(orgId, NotificationType.intervention_finish, language, {
interventionId,
});
};